package com.zilu.digitaltwin.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * @author :caijianbao
 * @date : 2023/1/3 20:20
 */
@Configuration
@MapperScan(basePackages = {"com.zilu.digitaltwin.dao.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MyBatisConfig {

    @Bean({"ds1"})
    @Primary
    @ConfigurationProperties("primary.datasource")
    public DataSource ds1() {
        return new DruidDataSource();
    }

    @Bean({"sqlSessionFactory1"})
    @Primary
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds1());
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    @Primary
    public DataSourceTransactionManager transactionManager(DataSource ds) throws Exception {
        return new DataSourceTransactionManager(ds);
    }
}
